﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Xml;
using System.Collections;
using System.Web.Caching;
namespace ToolsLayer
{
    public class ResourceManager
    {
        private static string ResourceFileName = HttpContext.Current.Server.MapPath("~\\AppString.xml");
        private static string MessageFileName = HttpContext.Current.Server.MapPath("~\\MessageString.xml");

        /// <summary>
        /// 从资源文件中取得一个字符串资源
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetString(string name)
        {
            //从缓存中取值
            Hashtable hs = (Hashtable)HttpContext.Current.Cache["AppString"];
            object o = null;
            try
            {
                o = hs[name].ToString();
            }
            catch
            {
                CacheStringResource();
                hs = (Hashtable)HttpContext.Current.Cache["AppString"];
                o = hs[name];
            }
        
            return o == null ? "字符串在资源文件中未找到" : o.ToString();
        }
        /// <summary>
        /// 在缓存中重新缓存整个字符串资源
        /// </summary>
        private static void CacheStringResource()
        {
            lock (typeof(ResourceManager))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(ResourceFileName);
                string xpath = "root/*";
                XmlNodeList nodes = xmlDoc.SelectNodes(xpath);
                if (nodes == null || nodes.Count == 0)
                    return;
                Hashtable h = new Hashtable();
                foreach (XmlNode n in nodes)
                {
                    h.Add(n.Attributes["name"].Value, n.InnerText);
                }
                CacheDependency dp = new CacheDependency(ResourceFileName);
                HttpContext.Current.Cache.Insert("AppString",
                        h, dp, DateTime.Now.AddHours(1), TimeSpan.Zero);
            }
        }

    }
}
